<?php
/**
 * Created by JetBrains PhpStorm.
 * User: leon
 * Date: 11/2/12
 * Time: 9:01 PM
 * To change this template use File | Settings | File Templates.
 */
namespace BWL\webshopBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use BWL\webshopBundle\Entity;
use JMS\SecurityExtraBundle\Annotation\Secure;

class ShoppingCartController extends Controller
{
  /**
   * @Secure(roles="ROLE_USER, ROLE_ADMIN")
   */
  public function showShoppingCartAction() {
    $user = $this->get('security.context')->getToken()->getUser();
    $em = $this->getDoctrine();
    $entries = $em->getRepository('BWLwebshopBundle:ShoppingCart')->findBy(array('user' => $user->getId()));
    $items = array();
    $totalPrice = 0;
    foreach($entries as $entry) {
      $itemEntry = array();
      $totalPrice += $entry->getItem()->getSalePrice() * $entry->getCount();
      array_push($itemEntry, $entry->getItem());
      array_push($itemEntry, $entry->getCount());
      array_push($items, $itemEntry);

    }
    return $this->render('BWLwebshopBundle:ShoppingCart:shoppingCart.html.twig', array('items' => $items, 'totalPrice' => $totalPrice));
  }

  /**
   * @Secure(roles="ROLE_USER, ROLE_ADMIN")
   */
  public function addToCartAction($id) {
    $user = $this->get('security.context')->getToken()->getUser();
    $em = $this->getDoctrine()->getManager();
    $entry = $em->getRepository('BWLwebshopBundle:ShoppingCart')->findBy(array('user' => $user->getId(), 'item' => $id));


    if($entry == null) {
      $item = $em->getRepository('BWLwebshopBundle:Item')->find($id);
      $entry = new \BWL\webshopBundle\Entity\ShoppingCart();
      $entry->setItem($item);
      $entry->setUser($user);
      $entry->setCount(1);
      $em->persist($entry);
    } else {
      $entry[0]->setCount($entry[0]->getCount() + 1);
    }
    $em->flush();

    return $this->redirect($this->generateUrl('bwl_webshop_shoppingCart'));
  }

  /**
   * @Secure(roles="ROLE_USER, ROLE_ADMIN")
   */
  public function removeFromCartAction($id) {
    $user = $this->get('security.context')->getToken()->getUser();
    $em = $this->getDoctrine()->getManager();
    $entry = $em->getRepository('BWLwebshopBundle:ShoppingCart')->findBy(array('user' => $user->getId(), 'item' => $id));
    foreach($entry as $entryItem) {
      $em->remove($entryItem);
    }
    $em->flush();
    return $this->redirect($this->generateUrl('bwl_webshop_shoppingCart'));
  }

  /**
   * @Secure(roles="ROLE_USER, ROLE_ADMIN")
   */
  public function orderNowAction() {
    $doctrine = $this->getDoctrine()->getManager();
    $user = $this->get('security.context')->getToken()->getUser();
    $orderStateOpen = $doctrine->getRepository('BWLwebshopBundle:OrderState')->findOneby(array('name' => 'open'));
    $shoppingCartItems = $doctrine->getRepository('BWLwebshopBundle:ShoppingCart')->findBy(array('user' => $user));
    $orderId = $this->getNewRandOrderId();
    $completePrice = 0;
    $orderItems = array();
    foreach($shoppingCartItems as $orderItem) {
      $item = $orderItem->getItem();
      $order = new \BWL\webshopBundle\Entity\Ordering();
      $order->setId($orderId);
      $order->setUser($user);
      $order->setItem($item);
      $order->setCount($orderItem->getCount());
      $order->setPrice($item->getSalePrice());
      $completePrice += $item->getSalePrice()*$orderItem->getCount();
      $order->setState($orderStateOpen);
      $doctrine->persist($order);
      $doctrine->remove($orderItem);
      $orderEntry =  array(
        'name' => $item->getName(),
        'count' =>$orderItem->getCount(),
        'price' =>$item->getSalePrice(),
        'totalPrice' => $item->getSalePrice() * $orderItem->getCount()
      );
      array_push($orderItems , $orderEntry);
    }
    $doctrine->flush();

    $name = array(
      'lastName' => $user->getLastName(),
      'firstName' => $user->getFirstName());;
    $message = \Swift_Message::newInstance()
      ->setSubject('Ihre Bestellung')
      ->setFrom('shop@bwl-webshop.de')
      ->setTo($user->getEmail())
      ->setBody($this->renderView('BWLwebshopBundle:ShoppingCart:orderEmail.txt.twig', array('orderItems' => $orderItems, 'name' => $name, 'completePrice' => $completePrice, 'orderId' => $orderId)));
    $this->get('mailer')->send($message);
    $this->get('session')->setFlash('blogger-notice', 'Your contact enquiry was successfully sent. Thank you!');

    return $this->redirect($this->generateUrl('bwl_webshop_shoppingCart'));
  }

  public function getNewRandOrderId() {
    $doctrine = $this->getDoctrine();
    do {
      $orderId = rand(1000000, 9999999);
      $shoppingCartItems = $doctrine->getRepository('BWLwebshopBundle:Ordering')->findBy(array('id' => $orderId));
    //  var_dump($shoppingCartItems);
    } while($shoppingCartItems != null);//number already used
    return ($orderId);
  }
}
